package com.xinyue.center.controller;

import java.util.Map;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.mygame.common.GameConstants;
import com.mygame.common.model.AccountToken;
import com.mygame.common.utils.JWTUtil;
import com.mygame.common.utils.RSAUtils;
import com.xinyue.center.dao.entity.Account;
import com.xinyue.center.logicconfig.GameCenterConfig;
import com.xinyue.center.messages.GameCenterError;
import com.xinyue.center.messages.request.LoginParam;
import com.xinyue.center.messages.response.GameGatewayInfoMsg;
import com.xinyue.center.messages.response.VoAccount;
import com.xinyue.center.service.GameGatewayService;
import com.xinyue.center.service.IAccountService;
import com.xinyue.center.service.model.GameGatewayInfo;
import com.xinyue.network.message.error.GameErrorException;
import com.xinyue.network.message.web.ResponseEntity;

@RestController
@RequestMapping("/user")
public class UserController {
	@Autowired
	private IAccountService accountService;
	@Autowired
	private GameGatewayService gameGatewayService;
	@Autowired
	private GameCenterConfig gameCenterConfig;

	private Logger logger = LoggerFactory.getLogger(UserController.class);

	@PostMapping("login")
	public ResponseEntity<VoAccount> login(@RequestBody LoginParam loginParam, HttpServletRequest request) {
		loginParam.checkParam();// 检测请求参数的合法性
		String loginIp = request.getRemoteAddr();
		loginParam.setLoginIp(loginIp);
		VoAccount userAccount = new VoAccount();
		Account account = null;
		Optional<Account> accountOp = accountService.login(loginParam);
		if (!accountOp.isPresent()) {
			account = accountService.register(loginParam);
		} else {
			account = accountOp.get();
		}
		BeanUtils.copyProperties(account, userAccount);
		String token = accountService.createUserToken(account);
		userAccount.setToken(token);
		
		return new ResponseEntity<VoAccount>(userAccount);
	}

//    @PostMapping("createPlayer")
//    public ResponseEntity<VoGameRole> createPlayer(@RequestBody CreatePlayerParam param, HttpServletRequest request) throws TokenException {
//        param.checkParam();
//        String userToken = request.getHeader(GameConstants.USER_TOKEN);
//        TokenContent tokenContent = JWTUtil.getTokenContent(userToken);
//        long userId = tokenContent.getUserId();
//        PlayerBasic player = playerService.createPlayer(param, userId);
//        accountService.addPlayer(userId, player);
//        VoGameRole playerBasic = playerService.getVoPlayer(player);
//
//        ResponseEntity<VoGameRole> response = new ResponseEntity<VoGameRole>(playerBasic);
//        return response;
//    }

	@PostMapping("selectGameGateway")
	public Object selectGameGateway(HttpServletRequest request)
			throws Exception {
		String userToken = request.getHeader(GameConstants.USER_TOKEN);
		AccountToken accountToken = JWTUtil.getTokenContent(userToken, AccountToken.class);
		Account account = accountService.selectAccount(accountToken.getAccountId());
		if(account == null) {
			GameCenterError.ACCOUNT_NOT_EXIST.throwError();
		}
		long playerId =account.getPlayerId();
		GameGatewayInfo gameGatewayInfo = gameGatewayService.getGameGatewayInfo(playerId).orElse(null);
		if (gameGatewayInfo == null) {
			throw GameErrorException.newBuilder(GameCenterError.NO_GAME_GATEWAY_INFO).build();
		}
		GameGatewayInfoMsg gameGatewayInfoMsg = new GameGatewayInfoMsg(gameGatewayInfo.getId(), gameGatewayInfo.getIp(),
				gameGatewayInfo.getPort());
		Map<String, Object> keyPair = RSAUtils.genKeyPair();// 生成rsa的公钥和私钥
		byte[] publickKeyBytes = RSAUtils.getPublicKey(keyPair);// 获取公钥
		String publickKey = Base64Utils.encodeToString(publickKeyBytes);// 为了方便传输，对bytes数组进行一下base64编码
		accountToken.setPublicKey(publickKey);
		accountToken.setGatewayIp(gameGatewayInfo.getIp());
		accountToken.updateExpireDays(gameCenterConfig.getPlayerTokenExpire());
		String token = JWTUtil.createToken(accountToken);
		gameGatewayInfoMsg.setToken(token);
		byte[] privateKeyBytes = RSAUtils.getPrivateKey(keyPair);
		String privateKey = Base64Utils.encodeToString(privateKeyBytes);
		gameGatewayInfoMsg.setRsaPrivateKey(privateKey);// 给客户端返回私钥
		logger.debug("player {} 获取游戏网关信息成功：{}", playerId, gameGatewayInfoMsg);
		ResponseEntity<GameGatewayInfoMsg> responseEntity = new ResponseEntity<>(gameGatewayInfoMsg);
		return responseEntity;
	}

}
